package org.vacoor.xqq.core.util;

import java.awt.*;

/**
 * 颜色转换工具类
 * <p/>
 * User: Vacoor
 */
public abstract class Colors {
    private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();

    private Colors() {
    }

    public static Color parseHtmlHexColor(String htmlColor) {
        if (htmlColor == null || !htmlColor.matches("#?(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})")) {
            return Color.BLACK;
        }
        return new Color(Integer.parseInt(htmlColor.replaceAll("^#", ""), 16));
    }

    public static String toHtmlHex(Color color) {
        return "#" + toHex(color.getRGB() | 0xFF000000); // clear alpha
    }

    public static String toHex(Color color) {
        return toHex(color.getRGB());
    }

    public static String toHex(int argb) {
        StringBuilder hex = new StringBuilder(8);
        hex.append(HEX_CHARS[(argb >> 28) & 0xF]).append(HEX_CHARS[(argb >> 24) & 0xF]); // alpha channel
        if ("FF".equals(hex.toString())) {
            hex.setLength(0);
        }
        hex.append(HEX_CHARS[(argb >> 20) & 0xF]).append(HEX_CHARS[(argb >> 16) & 0xF]) // red channel
                .append(HEX_CHARS[(argb >> 12) & 0xF]).append(HEX_CHARS[(argb >> 8) & 0xF]) // green channel
                .append(HEX_CHARS[(argb >> 4) & 0xF]).append(HEX_CHARS[(argb >> 0) & 0xF]); // blue channel
        return hex.toString();
    }
}
